package com.syezon.wifikey.splash.config;

import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.syezon.wifikey.ad.AdConfig;
import com.syezon.wifikey.utils.DateUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class SplashConfig {

    public static final String SPLASH_AD_SOURCE_DEFAULT = "default";
    public static final String SPLASH_AD_SOURCE_SELF = "ZY";
    public static final String SPLASH_AD_SOURCE_GDT = "GDT";
    public static final String SPLASH_AD_SOURCE_BD = "BD";
    public static final String SPLASH_AD_SOURCE_TT = "CSJ";
    public static final String SPLASH_AD_SOURCE_SG = "SG";

    public static final String DEFAULT_SPLASH_AD_ORDER = "CSJ,GDT,SG";
    private static final String CONFIG_NAME = "splash_order_config";
    private static final String SPLASH_SOURCE = "SPLASH_AD_SOURCE";
    private static final String LAST_SPLASH_AD_CODE = "last_splash_ad_code";
    private static final String SPLASH_AD_ORDER = "splash_ad_order";
    public static final String LAST_SPLASH_SHOW_DAY = "last_splash_show_day";
    private static final String SHOWED_AD_IDS = "showedADIds";
    public static final String YI_YOU_LIAO_NEWS_AD_COUNT = "yi_you_liao_news_ad_count";
    private static final String LAST_SPLASH_AD_TYPE = "last_splash_ad_type";
    public static HashMap<Integer, List<AdInfo>> maps;
    public static List<AdInfo> mPopAdOrderList;
    private static final String LAST_SPLASH_AD_OLD_TYPE = "last_splash_ad_old_type";

    /**
     * @return 获取开屏广告来源
     */
    public static String getSplashAdSource() {
        try {
            int checkCount = 0;
            String lastSplashAdCode = getLastSplashAdCode();
            String splashAdOrder = getSplashAdOrder();
            if (!TextUtils.isEmpty(splashAdOrder)) {
                String[] splashOrderArray = DEFAULT_SPLASH_AD_ORDER.split(",");
                if (splashOrderArray.length > 0) {
                    List<String> splashOrderList = new ArrayList<>(Arrays.asList(splashOrderArray));
                    splashOrderList.remove(lastSplashAdCode);
                    int lastSplashOrderIndex = splashOrderList.indexOf(lastSplashAdCode);
                    int splashAdCodeIndex = 0;
                    if (lastSplashOrderIndex != -1) {
                        int currentSplashOrderIndex = (lastSplashOrderIndex + 1) % splashOrderList.size();
                        splashAdCodeIndex = currentSplashOrderIndex;
                    }
                    while (checkCount < splashOrderList.size()) {
                        String splashAdCode = splashOrderList.get(splashAdCodeIndex % splashOrderList.size());
                        if ((SPLASH_AD_SOURCE_GDT.equals(splashAdCode) && AdConfig.canShowGDTAd())
                                || (SPLASH_AD_SOURCE_TT.equals(splashAdCode) && AdConfig.canShowCSJAd())
                                || (SPLASH_AD_SOURCE_SELF.equals(splashAdCode) && AdConfig.canShowSelfAd())
                        ) {
                            return splashAdCode;
                        } else {
                            splashAdCodeIndex++;
                            checkCount++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return SPLASH_AD_SOURCE_DEFAULT;
    }

    public static List<String> getSplashAdOrderList() {
        try {
            String splashAdOrder = getSplashAdOrder();
            if (!TextUtils.isEmpty(splashAdOrder)) {
                String[] splashOrderArray = splashAdOrder.split(",");
                if (splashOrderArray != null && splashOrderArray.length > 0) {
                    List<String> splashOrderList = new ArrayList<>(Arrays.asList(splashOrderArray));
                    return splashOrderList;
                }
            }
        } catch (Exception e) {

        }
        return Arrays.asList(SPLASH_AD_SOURCE_GDT, SPLASH_AD_SOURCE_TT, SPLASH_AD_SOURCE_SELF);
    }

    public static String getNextSplashAdCode(String currentSplashSourceCode, List<String> splashAdOrderList, int loadCount) {
        if (!TextUtils.isEmpty(currentSplashSourceCode) && splashAdOrderList != null && !splashAdOrderList.isEmpty()) {
            if (splashAdOrderList.size() == 1) {
                if (loadCount == 1) {
                    if (SPLASH_AD_SOURCE_GDT.equals(currentSplashSourceCode) && AdConfig.canShowCSJAd()) {
                        return SPLASH_AD_SOURCE_TT;
                    }
                    if (SPLASH_AD_SOURCE_TT.equals(currentSplashSourceCode) && AdConfig.canShowGDTAd()) {
                        return SPLASH_AD_SOURCE_GDT;
                    }
                    if (SPLASH_AD_SOURCE_SELF.equals(currentSplashSourceCode)) {
                        return SPLASH_AD_SOURCE_DEFAULT;
                    }
                } else {
                    return SPLASH_AD_SOURCE_DEFAULT;
                }
            }
            int checkCount = 0;
            int indexOf = splashAdOrderList.indexOf(currentSplashSourceCode);
            int splashAdCodeIndex = 0;
            if (indexOf != -1) {
                int nextSplashAdIndex = (indexOf + 1) % splashAdOrderList.size();
                splashAdCodeIndex = nextSplashAdIndex;
            }
            int size = splashAdOrderList.size();
            while (checkCount < size && loadCount <= size) {
                String splashAdCode = splashAdOrderList.get(splashAdCodeIndex % splashAdOrderList.size());
                if ((SPLASH_AD_SOURCE_GDT.equals(splashAdCode) && AdConfig.canShowGDTAd())
                        || (SPLASH_AD_SOURCE_TT.equals(splashAdCode) && AdConfig.canShowCSJAd())
                        || (SPLASH_AD_SOURCE_SELF.equals(splashAdCode) && AdConfig.canShowSelfAd())
                ) {
                    return splashAdCode;
                } else {
                    splashAdCodeIndex++;
                    checkCount++;
                }
            }
        }
        return SPLASH_AD_SOURCE_DEFAULT;
    }

    /**
     * @param source 设置开屏广告来源
     */
    public static void setSplashAdSource(int source) {
        SPUtils.getInstance(CONFIG_NAME).put(SPLASH_SOURCE, source);
    }

    /**
     * 获取上次开屏的序号
     *
     * @return
     */
    public static String getLastSplashAdCode() {
        int currentDayInt = DateUtil.getDayInt(new Date());
        int lastShowDayInt = SPUtils.getInstance(CONFIG_NAME).getInt(LAST_SPLASH_SHOW_DAY, 0);
        if (lastShowDayInt == currentDayInt) {
            return SPUtils.getInstance(CONFIG_NAME).getString(LAST_SPLASH_AD_CODE, "");
        } else {
            return "";
        }
    }

    /**
     * 保存上次开屏的序号
     *
     * @param
     */
    public static void saveLastSplashAdCode(String code) {
        SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_AD_CODE, code);
        int showDay = DateUtil.getDayInt(new Date());
        SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_SHOW_DAY, showDay);
    }

    /**
     * @param splashOrder 保存开屏广告顺序
     */
    public static void saveSplashAdOrder(String splashOrder) {
        SPUtils.getInstance(CONFIG_NAME).put(SPLASH_AD_ORDER, splashOrder);
    }

    /**
     * @return 获取开屏广告顺序
     */
    private static String getSplashAdOrder() {
        return SPUtils.getInstance(CONFIG_NAME).getString(SPLASH_AD_ORDER, DEFAULT_SPLASH_AD_ORDER);
    }

    public static void saveYiYouLiaoNewsAdCount(int count) {
        SPUtils.getInstance(CONFIG_NAME).put(YI_YOU_LIAO_NEWS_AD_COUNT, count);
    }

    public static void setAdList(List<AdInfo> adOrderList) {
        Collections.sort(adOrderList);
        clearSelfAD(adOrderList);
        mPopAdOrderList = adOrderList;
//        removeShowedAds();
        queryAllShowedAdsIdAndSetStatus();
        toMap(mPopAdOrderList);
    }

    private static void clearSelfAD(List<AdInfo> adOrderList) {
        boolean canShowSelfAd = AdConfig.canShowSelfAd();
        if (!canShowSelfAd) {
            for (int i = 0; i < adOrderList.size(); i++) {
                AdInfo currentAd = adOrderList.get(i);
                if (currentAd.getType() == AdInfo.AD_TYPE_WEB || currentAd.getType() == AdInfo.AD_TYPE_APK || currentAd.getType() == AdInfo.AD_TYPE_DEEPLINK) {
                    adOrderList.remove(i);
                    i--;
                }
            }
        }
    }

    /**
     * 初始化map之前，先对已经显示过的广告进行设置状态
     */
    private static void queryAllShowedAdsIdAndSetStatus() {
        //本地获取所有显示过的广告id
        String showedAdIds = getShowedAdIds();
        //本地没有广告id，则直接return
        if (TextUtils.isEmpty(showedAdIds)) {
            return;
        }
        //有则进行切割
        String[] adIds = showedAdIds.split(",");
        //如果广告id的长度和集合数组的长度不符合，那么直接清空本地的id缓存
        if (adIds.length >= mPopAdOrderList.size()) {
            LogUtils.e("广告缓存大于广告列表数据");
            clearShowedAdIds();
        } else {
            //否则开始循环，将对应id的AdInfo进行设置showed的状态
            for (String adId : adIds) {
                AdInfo adInfo = new AdInfo();
                adInfo.setId(Integer.parseInt(adId));
                int index = mPopAdOrderList.indexOf(adInfo);
                if (index != -1) {
                    mPopAdOrderList.get(index).setShowed(true);
                }
            }
        }
    }

    private static String getShowedAdIds() {
        int currentDayInt = DateUtil.getDayInt(new Date());
        int lastShowDayInt = SPUtils.getInstance(CONFIG_NAME).getInt(LAST_SPLASH_SHOW_DAY, 0);
        if (lastShowDayInt == currentDayInt) {
            return SPUtils.getInstance(CONFIG_NAME).getString(SHOWED_AD_IDS, "");
        } else {
            return "";
        }
    }

    private static void toMap(List<AdInfo> mPopAdOrderList) {
        LogUtils.e("陈超 toMap");
        maps = new HashMap<>();
        Collections.sort(mPopAdOrderList);
        for (AdInfo adInfo : mPopAdOrderList) {
            List<AdInfo> adInfos = maps.get(adInfo.getOrder());
            if (adInfos == null) {
                adInfos = new ArrayList<>();
                maps.put(adInfo.getOrder(), adInfos);
            }
            adInfos.add(adInfo);
        }
    }

    private static void clearShowedAdIds() {
        SPUtils.getInstance(CONFIG_NAME).put(SHOWED_AD_IDS, "");
    }

    /**
     * @return 获取广告来源 每次都会取下一个 已经最后一个则取第0个
     */
    public static AdInfo getNextAdSource() {
        try {
            //上次读取的广告对应的Order
            int lastVideoAdType = getLastSplashAdCodeInt();

            //上次读取的order返回空 并且广告Map没有数据，则直接返回null
            if (lastVideoAdType == -1 && (maps == null || maps.isEmpty())) {
                LogUtils.e("getNextAdSource 返回null");
                LogUtils.e("maps == null        " + (maps == null));
                LogUtils.e("maps.isEmpty()        " + (maps.isEmpty()));
                return null;
            }

            //根据广告类型取下一个键
            long mapKey = getNextMapKey(lastVideoAdType);

            //如果没有查询到对应的键，正常不会出现这种情况
            if (mapKey == -1) {
                return null;
            }

            List<AdInfo> adInfos = maps.get(Integer.parseInt(mapKey + ""));
            return randomAdInfos(adInfos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getLastSplashAdCodeInt() {
        int currentDayInt = DateUtil.getDayInt(new Date());
        int lastShowDayInt = SPUtils.getInstance(CONFIG_NAME).getInt(LAST_SPLASH_SHOW_DAY, 0);
        if (lastShowDayInt == currentDayInt) {
            return SPUtils.getInstance(CONFIG_NAME).getInt(LAST_SPLASH_AD_TYPE, -1);
        } else {
            return -1;
        }
    }

    /**
     * 根据广告类型取对应的键
     *
     * @param lastVideoAdType
     * @return
     */
    private static long getNextMapKey(long lastVideoAdType) {
        if (maps == null) {
            return -1;
        }
        //取到所有的键 order
        Set<Integer> integers = maps.keySet();
        int type = (int) lastVideoAdType;

        //将所有的order转为list
        ArrayList<Integer> arrayList = new ArrayList<>(integers);
        //如果没有取到对应的key，则取集合中的第一条
        if (lastVideoAdType == -1) {
            return arrayList.get(0);
        }
        //如果是在最后一条，那么也取第一条
        if (arrayList.indexOf(type) == arrayList.size() - 1) {
            return arrayList.get(0);
        }
        //如果不是不存在，或者不在最后一条，那么+1 取出
        int indexOf = arrayList.indexOf(type);

        return arrayList.get(++indexOf);
    }

    private static AdInfo randomAdInfos(List<AdInfo> adInfos) {
        ArrayList<AdInfo> noShowedList = new ArrayList<>();
        for (AdInfo adInfo : adInfos) {
            if (!adInfo.isShowed()) {
                noShowedList.add(adInfo);
            }
        }
        if (noShowedList.size() == 0) {
            for (AdInfo adInfo : adInfos) {
                adInfo.setShowed(false);
            }
            int i = new Random().nextInt(adInfos.size());
            return adInfos.get(i);
        } else {
            int i = new Random().nextInt(noShowedList.size());
            return noShowedList.get(i);
        }
    }

    /**
     * 易有料新闻广告插入间隔
     *
     * @return
     */
    public static int getYiYouLiaoNewsAdCount() {
        return SPUtils.getInstance(CONFIG_NAME).getInt(YI_YOU_LIAO_NEWS_AD_COUNT);
    }

    public static void saveLastSplashAd(AdInfo adInfo) {
        if(adInfo == null){
            return;
        }
        adInfo.setShowed(true);
        checkOrderAdInfos(adInfo);
        SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_AD_TYPE, adInfo.getOrder());
        int showDay = DateUtil.getDayInt(new Date());
        SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_SHOW_DAY, showDay);
    }

    private static void checkOrderAdInfos(AdInfo adInfo) {
        List<AdInfo> adInfos = maps.get(adInfo.getOrder());

        //标志位
        boolean isAllShowed = true;
        if(adInfos == null){
            isAllShowed = false;
        }else {
            for (AdInfo info : adInfos) {
                //如果有不满足的，则直接设为false，并且退出循环
                if (!info.isShowed()) {
                    isAllShowed = false;
                    break;
                }
            }
        }

        //如果全部都显示过了
        if(isAllShowed){
            //获取本地存储的所有显示过的广告id
            String ids = getShowedAdIds();
            //拆分id到集合当中
            String[] split = ids.split(",");
            List<String> splashOrderList = new ArrayList<>(Arrays.asList(split));
            //将对应的广告设置为不显示，并且移除记录id的集合对应的id
            for (AdInfo info : adInfos) {
                if(adInfos.size() != 1 && adInfo == info){
                    continue;
                }
                info.setShowed(false);
                splashOrderList.remove(info.getId() + "");
            }
            //剩余的广告id重新存储到本地
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < splashOrderList.size(); i++) {
                sb.append(splashOrderList.get(i));
                if(i != splashOrderList.size() - 1) {
                    sb.append(",");
                }
            }

            SPUtils.getInstance(CONFIG_NAME).put(SHOWED_AD_IDS, sb.toString());
        }else {
            String ids = getShowedAdIds();
            StringBuilder sb = new StringBuilder();
            //把ids放进StringBuilder中
            sb.append(ids);
            //判断是否已经存有id，如果为空，则直接添加
            if (TextUtils.isEmpty(sb.toString())) {
                sb.append(adInfo.getId());
                //如果已经存有id，则判断是否不包含该id，如果不包含，则添加
            } else if (!ids.contains(adInfo.getId() + "")) {
                sb.append(",");
                sb.append(adInfo.getId());
            }
            SPUtils.getInstance(CONFIG_NAME).put(SHOWED_AD_IDS, sb.toString());
        }
    }

    /**
     * 保存每次新协议已经读取的code
     * @param adInfo
     */
    public static void saveLastSplashOldAdCode(AdInfo adInfo) {
        switch (adInfo.getType()) {
            case AdInfo.AD_TYPE_GUANG_DIAN_TONG:
                SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_AD_OLD_TYPE, SPLASH_AD_SOURCE_GDT);
                break;
            case AdInfo.AD_TYPE_CHUAN_SHAN_JIA:
                SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_AD_OLD_TYPE, SPLASH_AD_SOURCE_TT);
                break;
            case AdInfo.AD_TYPE_APK:
            case AdInfo.AD_TYPE_WEB:
            case AdInfo.AD_TYPE_DEEPLINK:
                SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_AD_OLD_TYPE, SPLASH_AD_SOURCE_SELF);
                break;
        }
        int showDay = DateUtil.getDayInt(new Date());
        SPUtils.getInstance(CONFIG_NAME).put(LAST_SPLASH_SHOW_DAY, showDay);
    }
}
